package com.lhl.shiro.shiroconfig;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author LHL
 * @date 2018/1/8
 */

public class TokenProcessor {

    private static TokenProcessor instance = new TokenProcessor();

    private long previous;

    private TokenProcessor() {
    }

    public static TokenProcessor getInstance() {
        return instance;
    }

    public synchronized String generateToken(String msg, boolean timeChange) {
        try {
            long current = System.currentTimeMillis();
            if (current == previous) {
                current++;
            }
            previous = current;
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(msg.getBytes());
            if (timeChange) {
                byte[] now = Long.toString(current).getBytes();
                md.update(now);
            }
            return toHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    private String toHex(byte[] buffer) {
        StringBuilder sb = new StringBuilder(buffer.length * 2);
        for (byte aBuffer : buffer) {
            sb.append(Character.forDigit((aBuffer & 240) >> 4, 16));
            sb.append(Character.forDigit(aBuffer & 15, 16));
        }
        return sb.toString();
    }
}